package com.code.penguin.bots;

import com.alibaba.fastjson.JSON;
import com.code.penguin.enums.SystemKeyEnum;
import com.code.penguin.models.ChatMemberGroup;
import com.code.penguin.models.RobotChat;
import com.code.penguin.services.ChatMemberGroupService;
import com.code.penguin.services.RobotChatService;
import com.code.penguin.services.RobotSystemService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 加群机器人
 *
 * @author xiaoyaowang
 */
public class ListenBot extends TelegramLongPollingBot {

    private static Logger logger = LoggerFactory.getLogger(ListenBot.class);

    private String robotName;

    private String robotToken;

    private String listenJoinGroupUrlPrefix;

    private String listenJoinGroupName;

    private RobotChatService robotChatService;

    private RobotSystemService robotSystemService;

    private ChatMemberGroupService chatMemberGroupService;

    public void setRobotName(String robotName) {
        this.robotName = robotName;
    }

    public void setRobotToken(String robotToken) {
        this.robotToken = robotToken;
    }

    public void setListenJoinGroupUrlPrefix(String listenJoinGroupUrlPrefix) {
        this.listenJoinGroupUrlPrefix = listenJoinGroupUrlPrefix;
    }

    public void setListenJoinGroupName(String listenJoinGroupName) {
        this.listenJoinGroupName = listenJoinGroupName;
    }

    public void setRobotChatService(RobotChatService robotChatService) {
        this.robotChatService = robotChatService;
    }

    public void setRobotSystemService(RobotSystemService robotSystemService) {
        this.robotSystemService = robotSystemService;
    }

    public void setChatMemberGroupService(ChatMemberGroupService chatMemberGroupService) {
        this.chatMemberGroupService = chatMemberGroupService;
    }

    @Override
    public String getBotUsername() {
        return robotName;
    }

    @Override
    public String getBotToken() {
        return robotToken;
    }

    @Override
    public void onUpdateReceived(Update update) {
        logger.info("listen join group bot start work,execute onUpdateReceived method，update:{}", update.toString());
        try {
            if (update.hasMessage()) {
                Message messageText = update.getMessage();
                if (null != messageText) {
                    Long chatIdLong = messageText.getChatId();
                    if (null != chatIdLong) {
                        String chatId = chatIdLong.toString();
                        // 插入用户或者群组与机器人的绑定关系
                        RobotChat robotChat = new RobotChat();
                        robotChat.setChatId(chatId);
                        robotChat.setRobotName(robotName);
                        robotChatService.insertRobotChat(robotChat);

                        // 保存加群记录
                        String stopRobot = robotSystemService.getSystemValueBySystemKey(SystemKeyEnum.STOP_ROBOT.name());
                        if ("1".equals(stopRobot)) {
                            return;
                        }
                        String groupUrl = null;
                        Chat chat = messageText.getChat();
                        String userName = chat.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            groupUrl = listenJoinGroupUrlPrefix + userName;
                        }
                        String joinGroupUrl = listenJoinGroupUrlPrefix + listenJoinGroupName;
                        if (!joinGroupUrl.equals(groupUrl)) {
                            return;
                        }
                        List<User> newChatMembers = messageText.getNewChatMembers();
                        logger.info("new chat members:{}", JSON.toJSONString(newChatMembers));
                        List<ChatMemberGroup> chatMemberGroupList = null;
                        if (!CollectionUtils.isEmpty(newChatMembers)) {
                            chatMemberGroupList = new ArrayList<>(newChatMembers.size());
                            Boolean isBot;
                            ChatMemberGroup chatMemberGroup;
                            String newChatId;
                            for (User newChatMember : newChatMembers) {
                                chatMemberGroup = new ChatMemberGroup();
                                chatMemberGroup.setGroupUrl(groupUrl);
                                newChatId = String.valueOf(newChatMember.getId());
                                chatMemberGroup.setChatId(newChatId);
                                if (!chatMemberGroupService.judgeUserWhetherJoinGroup(chatMemberGroup)) {
                                    chatMemberGroup.setGroupName(chat.getTitle());
                                    chatMemberGroup.setUserName(newChatMember.getUserName());
                                    chatMemberGroup.setFirstName(newChatMember.getFirstName());
                                    chatMemberGroup.setLastName(newChatMember.getLastName());
                                    isBot = newChatMember.getIsBot();
                                    if (isBot) {
                                        chatMemberGroup.setIsBot(1);
                                    } else {
                                        chatMemberGroup.setIsBot(0);
                                    }
                                    chatMemberGroup.setDeleted(0);
                                    chatMemberGroup.setCreatedAt(new Date());
                                    chatMemberGroup.setUpdatedAt(new Date());
                                    chatMemberGroupList.add(chatMemberGroup);
                                }

                            }
                        } else {
                            User from = messageText.getFrom();
                            logger.info("from User:{}", JSON.toJSONString(from));
                            if (null != from) {
                                chatMemberGroupList = new ArrayList<>(1 << 2);
                                ChatMemberGroup chatMemberGroup = new ChatMemberGroup();
                                chatMemberGroup.setGroupUrl(groupUrl);
                                String fromChatId = String.valueOf(from.getId());
                                // 统计在群里发送消息的次数
//                                robotChatService.incrementChatMessageNums(fromChatId);
                                chatMemberGroup.setChatId(fromChatId);
                                if (!chatMemberGroupService.judgeUserWhetherJoinGroup(chatMemberGroup)) {
                                    chatMemberGroup.setGroupName(chat.getTitle());
                                    chatMemberGroup.setUserName(from.getUserName());
                                    chatMemberGroup.setFirstName(from.getFirstName());
                                    chatMemberGroup.setLastName(from.getLastName());
                                    boolean isBot = from.getIsBot();
                                    if (isBot) {
                                        chatMemberGroup.setIsBot(1);
                                    } else {
                                        chatMemberGroup.setIsBot(0);
                                    }
                                    chatMemberGroup.setDeleted(0);
                                    chatMemberGroup.setCreatedAt(new Date());
                                    chatMemberGroup.setUpdatedAt(new Date());
                                    chatMemberGroupList.add(chatMemberGroup);
                                }
                            }
                        }
                        if (!CollectionUtils.isEmpty(chatMemberGroupList)) {
                            chatMemberGroupService.insertChatMemberGroupList(chatMemberGroupList);
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("onUpdateReceived error:", e);
        }


    }

}
